import { message } from 'antd';
import { useCallback, useMemo, useState } from 'react';
import { useRequest } from 'umi';
import { getOrgPosition } from '../service';
import { usePositionTreeData } from './usePositionTreeData';

export const usePositionData = (curRes: any) => {
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]); //树选中的key

  /* 获取右边岗位信息数据 */
  const orgPostion = useRequest(
    (id: string) => {
      return getOrgPosition({
        id,
      });
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
        }
      },
    },
  );

  /* 点击树调用信息切换 */
  const onTreeSelectChange = useCallback(
    (id: string) => {
      if (id) {
        setSelectedKeys([id]);
        orgPostion.run(id);
      }
    },
    [selectedKeys],
  );

  const { orgTreeData, treeLoading, getTreeData } = usePositionTreeData(
    onTreeSelectChange,
    curRes,
  );

  /* 列表数据 */
  const orgTableData = useMemo(() => {
    return {
      dataSource: orgPostion.data?.obj,
      tableLoading: orgPostion.loading,
    };
  }, [orgPostion.data, orgPostion.loading]);

  const onTableReload = () => {
    const [id] = selectedKeys;

    if (id) {
      orgPostion.run(id);
    }
  };

  return {
    orgTreeData,
    treeLoading,
    onTreeSelectChange,
    getTreeData,
    selectedKeys,
    onTableReload,
    ...orgTableData,
  };
};
